<?php
// 当前文件所在目录
$currentDir = dirname(__FILE__);

// 检查配置文件
if (!file_exists($currentDir . '/list.conf')) {
    copy($currentDir . '/list.conf.example', $currentDir . '/list.conf');
}
$confList = explode("\n", file_get_contents($currentDir . '/list.conf'));

function modify($confFile, $ip) {
    $content = file_get_contents($confFile);
    $content = preg_replace(
        '/allow(\s+)([0-9]{1,3}\.){3}[0-9]{1,3};\s*#\s*dev.zayagame.com/',
        "allow {$ip}; # dev.zayagame.com",
        $content);
    file_put_contents($confFile, $content);
}

function getIP() {
    $output = [];
    exec('nslookup dev.zayagame.com', $output);
    if (isset($output[5])) {
        $ip = explode(' ', $output[5])[1];
        $pat = "/^([0-9]{1,3}\.){3}[0-9]{1,3}$/";
        if (preg_match($pat,$ip)){
            message("获取到当前外网IP:$ip");
            return $ip;
        }
    }
    return false;
}

function isChangeIP($newIP) {
    $logFile = '/var/log/dev.zayagame.com/lastIP.log';
    if (!file_exists($logFile)) {
        mkdir(dirname($logFile), 0777, true);
        file_put_contents($logFile, '');
    }
    $oldIP = file_get_contents($logFile);
    if ($oldIP == $newIP) {
        message('当前devIP与记录devIP相同');
        return false;
    } else {
        file_put_contents($logFile, $newIP);
        message("当前devIP:$newIP\n记录devIP:$oldIP\n更新");
        return true;
    }
}

function message($message) {
    $debug = false;
//    $debug = true;
    if (!$debug) return;
    if (is_string($message)) {
        echo $message, "\n";
    } else {
        var_dump($message);
    }
}

if (!$ip = getIP()) {
    message('获取不到当前外网IP');
    return;
}
if (!isChangeIP($ip)) {
    return;
}

foreach ($confList as $confFile) {
    if (!is_file($confFile)) {
        continue;
    }
    modify($confFile, $ip);
}
exec('/usr/sbin/nginx -s reload');